package com.ag.webservice;

import java.net.MalformedURLException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.xfire.client.XFireProxyFactory;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.service.binding.ObjectServiceFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.ag.admin.dao.AdminTbUserDAO;
import com.ag.bean.TbRole;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserDept;
import com.ag.bean.TbUserRole;
import com.ag.bean.TbUserState;
import com.ag.common.IDUtil;
import com.ag.contactTree.service.LocalTreeService;
import com.ag.dao.TbContactDAO;
import com.ag.dao.TbDeptDAO;
import com.ag.dao.TbOaContactDAO;
import com.ag.dao.TbRoleDAO;
import com.ag.dao.TbUserDeptDAO;
import com.ag.zhh.dao.DeptDAO;
import com.ag.zhh.vo.TbDeptUserLinkTable;
import com.dcampus.user.webservice.I_Group;
import com.dcampus.user.webservice.I_ObjectService;
import com.dcampus.user.webservice.I_User;

/**
 * 我的
 * OA通讯录同步Service类
 * 
 * @author 万才
 * 
 */
public class LwcOAsynchronism extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(OAUserService.class);

	private static I_ObjectService service = null;
	static String ROLE_ID = "admin";
	static String SYSTEM_ID = "Student Management System";// ssm.getSubSystems()[0].getId();
	static String CATEGORY_ID = "user-manage";
	static String FUNCTION_ID = "view-user";

	static {
		Service serviceModel = new ObjectServiceFactory()
				.create(I_ObjectService.class);

		String serviceURL = "http://cas.gzfda.gov.cn/services/UserObjectService";
		// String serviceURL = "http://heaven.net/services/UserObjectService";

		try {
			service = (I_ObjectService) new XFireProxyFactory().create(
					serviceModel, serviceURL);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}
	@Resource(name = "DeptDAO")
	private DeptDAO deptDAO;
	@Resource(name = "TbContactDAO")
	private TbContactDAO contactDAO;
	@Resource(name = "TbOaContactDAO")
	private TbOaContactDAO oaContactDAO;
	@Resource(name = "TbDeptDAO")
	private TbDeptDAO tbDeptDAO;
	@Resource(name="adminTbUserDAO")
	private AdminTbUserDAO userDAO;
	@Resource(name="TbUserDeptDAO")
	private TbUserDeptDAO userDeptDAO;
	@Resource(name="LocalTreeService")
	private LocalTreeService localtreeservice;
	@Resource(name="TbRoleDAO")
	private TbRoleDAO roledao ;
	
	
	/**
	 * 主方法：保存所有OAuser（未完成）
	 * 用户部门表不存在的部门不能插
	 * 
	 * 1.在OA系统中获取所有的用户
	 * 第一个事务开始
	 * 2.根据用户编码找到对应的部门，绑定用户和部门的关系
	 * 3.更新这批用户并设同步标志位为1
	 * 
	 * 第二个事务开始
	 * 4.将同步标志位为0的oa用户查出来，断开中间表，并设为删除状态 		WHERE (OA_CODE IS NOT NULL) AND (OA_IS_UPDATE = 0) 
	 * 5.将所有的oa用户的同步标志位设为0
	 * 
	 */
	public void saveAllOAUser()
	{ 
		
		//1.获取所有OAUSER
		I_User[] users = this.getAllOAUser();		
		Session session = this.getSessionFactory().openSession();
		Transaction tx1 = null;
		//2.根据用户编码找到对应的部门，绑定用户和部门的关系
		//第一个事务
		try
		{	
			tx1 = session.beginTransaction();
			int isexit = 0;
			TbUserState state = (TbUserState) session.get(TbUserState.class, "1001");	//用户状态
			for (I_User user : users)
			{
				System.out.println(user.getAddress());
				
				if("00".equals(user.getCode()))
				{
					
				}
				else if(user.getCode()==null)
				{
					
				}
				else if(user.getName()!=null&&user.getName().length()>=8)					//人名长度大于4个字
					continue;
				else
				{
					isexit = 0;						//同步过来的用户,0为存在，1为不存在
					
					TbUserDept dept = null;
					//将户的部门查出来
					dept = this.findByUserCode(session, user.getCode());
//					if(dept==null) continue;//dgm
					if(dept==null){
						
						System.out.println("dept==null");
						continue;
					}
					
					
					
					//将用户查出来
					TbUser contact = (TbUser) session.get(TbUser.class, user.getId());
					//用户为空的话，就新建一个
					if(contact == null)
					{
						isexit = 1;
						contact = new TbUser();
						contact.setUId(user.getId());
					 }
					contact = packIUserIntoUser(user,contact);
					
					contact.setTbUserState(state);			//初始化用户状态
					//处理中间表
					TbDeptUserLinkTable  linktable = new TbDeptUserLinkTable();
					linktable.setUid(user.getId());
					linktable.setUdid(dept.getUdId());
					System.out.println(contact.getUName()+"**");
					session.saveOrUpdate(contact);			//保存用户
					session.saveOrUpdate(linktable);		//保存中间表
				}
				
			}
			tx1.commit();
		}
		catch (HibernateException e)
		{
			tx1.rollback();
			e.printStackTrace();
		}
		session.close();
		//第二个事务
		//4.将同步标志位为0的oa用户查出来，断开中间表，并设为删除状态 ,用于删除多于的用户
	
		session=this.getSessionFactory().openSession();
		Transaction tx2 = null;
		
		try {
			tx2 = session.beginTransaction();
			
			//查出要删除的用户
			List<TbUser> contacts = (List<TbUser>) session.createSQLQuery("select * from TB_USER WHERE (OA_CODE IS NOT NULL) AND (OA_IS_UPDATE = 0)").addEntity(TbUser.class).list();
			
			//断开中间表
			for(TbUser u:contacts)
			{
				TbDeptUserLinkTable  linktable = (TbDeptUserLinkTable) session.get(TbDeptUserLinkTable.class, u.getUId());
				if(linktable!=null) session.delete(linktable);
				u.setA(IDUtil.DELETE);
			}
	
			tx2.commit();
			
			//恢复同步标志位
			Query query = session.createSQLQuery("update tb_user set oa_is_update = 0");
			query.executeUpdate();
		}
		catch (HibernateException e)
		{
			tx2.rollback();
			e.printStackTrace();
		}
		session.close();
		
	//	localtreeservice.updateTree();				//更新树
		initRole();									//初始化角色
		
	}
	
	/**
	 * 根据用户的编码，查找对应的部门出来
	 * @param session
	 * @param userCode
	 * @return
	 */
	public TbUserDept findByUserCode(Session session,String userCode)
	{
		TbUserDept dept = null;
		System.out.println("userCode为 ："+userCode);
		if(userCode.length()<6){
			return null;
		}
		userCode = (String) userCode.subSequence(0,6);
//		userCode = (String) userCode.subs
		System.out.println("从oa同步过来的部门编码： "+userCode);
		
		List<TbUserDept> list = null;
		Query query = session.createQuery("from TbUserDept as model where model.GCode = :gCode").setString("gCode", userCode);
		System.out.println("*******");
		list = (List<TbUserDept>)query.list();
		System.out.println("能否查出部门？"+list.size());
		if(list.size()>0) 
		{
			dept = list.get(0);
			System.out.println(dept.getUdName());
		}
			
		return dept;
	}
	
	
	/**
	 * 将IUser打包返回一个新的OA通讯录对象（完成）
	 * 
	 * @param user
	 * @return
	 */
	private static TbUser packIUserIntoUser(I_User user,TbUser contact)
	{
	//	contact.setUPassword(user.get)
		contact.setUPhone(user.getMobilePhoneNumber());
		//System.out.print("电话号码："+user.getPhoneNumber()+"*********");
		contact.setUTel(user.getPhoneNumber());
		contact.setUName(user.getName());
		contact.setOaAddress(user.getAddress());
		contact.setOaCode(user.getCode());
		contact.setOaDescri(user.getDescription());
		contact.setOaGender(user.getGender());
		contact.setOaHomeNumber(user.getHomeNumber());
		contact.setOaIdCard(user.getIdCard());
		contact.setUMail(user.getMail());
		contact.setOaMsn(user.getMsn());
		contact.setOaOfficeNumber(user.getOfficeNumber());
		contact.setOaQq(user.getQq());
		contact.setOaSex(user.getSex());
		contact.setOaZipCode(user.getZipCode());
		contact.setA("0");
		System.out.println("posistons:"+user.getPositions()+"\t"+user.getPositions().length);
		if(user.getPositions()!=null&&user.getPositions().length>=1) 
			contact.setOaPositions(user.getPositions()[0]);
		contact.setOaIsUpdae(1);					//设置同步标志位为1	
		if(user.getGroups() != null && user.getGroups().length > 0)
		{
			String[] groups = user.getGroups();		
			contact.setOaGroups(groups[0]);
		}
		System.out.println("pickup "+contact.getUName());
		/*
		Set<TbUserDept> userDepts = contact.getTbUserDepts();
		if(userDepts == null) {
			userDepts = new HashSet<TbUserDept>();
		}
		userDepts.add(dept);
		contact.setTbUserDepts(userDepts);
		Set<TbUser> users = dept.getTbUsers();
		users.add(contact);
		dept.setTbUsers(users);	
		 user.getRoles()	
		 user.getPositions()
		 user.getGroups()
	
		 */
		return contact;
	}

	/**
	 * 访问OA系统，获取所有OA通讯录人
	 * 
	 * @return
	 */
	private I_User[] getAllOAUser() {
		I_User[] users = null;
//		I_User[] users = null;
		
		try {
			users = service.getAllUsers();
			if (users == null || users.length == 0) {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("OAUserService:getAllOAUser:异常");
			throw new RuntimeException("OAUserService:getAllOAUser:异常");
		}
		return users;
	}
/*
	public I_User[] getAllOAUser2()
	{
		return OADataPare.getAllOAUser();
	}
	*/
	/**
	 * 返回用户的组id，暂时不知道怎用
	 * @param groupId
	 * @return
	 */
	private I_Group getGroupByGId(String groupId) {
		I_Group group = null;
		try {
			group = service.getGroupOfId(groupId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return group;
	}
	
	/**
	 * 保存一个部门,暂时不知道怎用
	 * @param group
	 * @return
	 */
	public TbUserDept saveOneGroup(I_Group group) {
		TbUserDept dept = new TbUserDept();
		dept.setUdId(group.getId());
		dept.setGId(group.getId());
		//dept.setDName(group.getName());
		dept.setGCode(group.getCode());
		dept.setGDesc(group.getDescription());
		// StringBuilder admin = new StringBuilder();
		// for(String sadmin:group.getManagers()) {
		// admin.append(sadmin);
		// admin.append(",");
		// }
		// admin.substring(0, admin.length()-1);
		// dept.setGAdmin(admin.toString());
		//tbDeptDAO.attachDirty(dept);
		return dept;
	}
	

	/**
	 * 访问OA系统，获取所有OA部门
	 * 
	 * @return
	 */
	public I_Group[] getAllOAGroup() 
	{
		I_Group[] groups = null;
		try
		{
			groups = service.getAllGroups();
			if (groups == null || groups.length == 0) {
				return null;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.error("OAUserService:getAllOAGroup:异常");
			throw new RuntimeException("OAUserService:getAllOAGroup:异常");
		}
		return groups;
	}
	
	/**
	 * 同步结束后要初始化用户的角色
	 */
	public void initRole()
	{	
		TbRole role = null;
		Transaction tx = null;
		Session session = roledao.getSessionFactory().openSession();
		try
		{
			tx = session.beginTransaction();
			//加载要被初始化的角色
			role =(TbRole) session.get(TbRole.class, "1017");
			System.out.println("角色id："+role.getRId()+" \t角色："+role.getRName());		
			List<TbUser> users = session.createQuery("from TbUser").list();
			int size=0;
			for(TbUser user:users)
			{
				//如果该用户没有角色
				if(user.getTbUserRoles().size()==0)
				{
					size=size+1;
					System.out.print(user.getUId()+"\t"+user.getUName()+"\t");
					//新增一个用户角色
					TbUserRole userrole = new TbUserRole();
					userrole.setTbUser(user);
					userrole.setTbRole(role);
					userrole.setA("0");
					user.getTbUserRoles().add(userrole);		//加入到用户的用户角色当中
					role.getTbUserRoles().add(userrole);		//加入到角色的用户角色当中	
					
				}
				
			}
			System.out.println("\n\n\t\t没有角色的用户的数目："+size);
			tx.commit();
		}
		catch(Exception e)
		{
			tx.rollback();
		}
		finally{
			session.close();
		}
		localtreeservice.updateTree();				//更新树
	}

}

